﻿var Logger = {
	log: function(obj) {
		if (obj.indexOf != null) {
			console.log('[' + (new Date().format('dd/MM/yyyy hh:mm:ss'))+']' + obj);
		} else {
			console.log(obj);
		}
	}
}

//BEING SAMPLE DATA
function SampleLoader(size, gr) {
	this.data = [];
	this.get = function(from, to, callback) {
		var _this = this;
		setTimeout(function() {
			callback({
				items: _this.data.slice(from, to),
				total: _this.data.length
			});
		}, $('#delay').val());
	};
	
	this.init = function() {
		for (var i=0;i < size;i++)  {
			this.data.push(gr(i, size));
		}
	};
	
	this.init();
};

var dt;

function DefaultInputEditor() {
	this.attach = function(el, value, valueChanged) {
		var inp = $('<input>').val(value);
		
		inp.css('margin', '0px').
			css('padding', '0px').
			css('outline', 'none').
			css('border', '0px').
			css('background', 'transparent').
			css('font-size', $(el).css('font-size')).
			css('font-family', $(el).css('font-family'));
		
		inp.width($(el).width()-2);
		inp.dblclick(function(e) {
			e.cancelBubble = true;
			e.stopPropagation();
		});
		inp.focus(function() {
			this.select();
		});
		inp.keydown(function(e) {
			switch(e.keyCode) {
				case 13: 
					valueChanged(this.value);
					break;
				case 27:
					valueChanged(this.value, true);
				default:
					break;
			}
			e.cancelBubble = true;
			e.stopPropagation();
		});
		inp.blur(function() {
			valueChanged(this.value);
		});
		$(el).append(inp);
		inp.focus();
		return inp;
	}
};

function DateInputEditor() {
	this._default = new DefaultInputEditor();
	this.attach = function(el, value, valueChanged) {
		var inp = this._default.attach(el, value, valueChanged);
		inp.datepicker();
		return inp;
	};
}

function DateRenderer(format) {
	this.render = function(column, record) {
		if (record[column.field] != null) {
			return record[column.field].format(format);
		} else {
			throw new Error("yo");
		}
	};
	
	this.renderValue = function(column, record) {
		return record[column.field].format(format);
	};
};

function CheckboxRenderer() {
	this.render = function(column, record) {
		var cb = $('<input>').attr('type', 'checkbox').attr('checked', record[column.field]);
		cb.click(function(e) {
			var value = cb.attr('checked') == 'checked';
			record[column.field] = value;
			var row = $(getFirstAncestorOfType(cb.get(0), 'TR'));
			if (value) row.addClass('ui-selected'); else row.removeClass('ui-selected'); 
			e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation();
		});
		return cb;
	};
	
	this.renderValue = function(column, record) {
		return record[column.field];
	};
};


function Themes(themes, listbox) {
	var _this = this;
	this.themes = themes;
	this.currentTheme = null;
	
	this.getTheme = function(name) {
		for (var i=0;i<themes.length;i++) {
			if (themes[i].name == name) return themes[i];
		}
	};
	this.setTheme = function(name) {
		window.query.set('theme', name);
		this.currentTheme = this.getTheme(name);
		if (this.currentTheme == null) {
			alert('Could not find theme ' + name);
		} else {
			document.getElementById('themecss').href = _this.currentTheme.file;
		}
	}
	
	if(window.query.contains('theme')) {
		this.setTheme(query.get('theme'));
	} else {
		this.setTheme(themes[0].name);
	}
	
	for (var i=0;i<themes.length;i++) {
		$(listbox).append($('<option>').attr('selected', themes[i] == this.currentTheme).attr('value', themes[i].name).html(themes[i].title));
	}
	$(listbox).change(function() {
		_this.setTheme($(this).val());
	})
}

function Query(charSplit) {
	var _this = this;
	this.query = new Map();
	this.set = function(key, val) {
		this.query.put(key, val);
	};
	this.get = function(key) {
		return this.query.get(key);
	};
	this.contains = function(key) {
		return this.query.contains(key);
	};
	if (document.location.href.indexOf(charSplit) > -1) {
		var queryString = decodeURI(document.location.href.split(charSplit)[1]);
		var params = queryString.split('&');
		for (var i=0;i<params.length;i++) {
			var keyval = params[i].split('=');
			this.query.put(keyval[0], keyval[1]);
		}
	}
	
	this.onquerychange = function() {
		var queryString = [];
		for (var i=0;i < _this.query.size();i++) {
			queryString.push(_this.query.map[i].key + '=' + _this.query.map[i].value);
		}
		queryString = charSplit + queryString.join('&');
		
		document.location.href = queryString;
	};
	
	if (this.query.change.index(this.onquerychange) == null) this.query.change.add(this.onquerychange);
}

function togglePlugin(reference, active, options) {
	if (dt.plugins.contains(reference)) {
		Logger.log('Deregistering plugin ' + reference);
		dt.plugins.remove(reference);
	}
	
	if (active) {
		window.plugins.put(reference, options);
		Logger.log('Registering plugin ' + reference + ": " + JSON.stringify(options));
		var plugin = null;
		
		if (reference == 'toolbar') plugin = new DatatableToolbarPlugin(options);
		if (reference == 'title') plugin = new TableTitleHandler(options);
		if (reference == 'oddeven') plugin = new OddEvenRowHandler(options);
		if (reference == 'celledit') plugin = new CellEditHandler(options);
		if (reference == 'search') plugin = new SearchHandler(options);
		if (reference == 'filter') plugin = new FilterHandler(options);
		if (reference == 'sort') plugin = new ColumnSortHandler(options);
		if (reference == 'navigate') plugin = new CellNavigateHandler(options);
		if (reference == 'hover') plugin = new RowHoverHandler(options);
		if (reference == 'select') plugin = new RowSelectionHandler(options);
		if (reference == 'presenter') plugin = new PresenterHandler(options);
		if (reference == 'view') plugin = new ViewHandler(options);
		
	
		plugin.stateChanged.add(function() {
			window.query.set(reference, JSON.stringify(plugin.state));
		});
		
		
		dt.plugins.add(reference, plugin, options);
	} else {
		window.plugins.remove(reference);
	}
	
	//updating query string
	window.query.set('plugins', dt.plugins.plugins.getKeys().join(','));
	for (var i = 0; i < window.plugins.size(); i++) {
		var key = window.plugins.getKeyByIndex(i);
		if (window.plugins.get(key)) {
			window.query.set(key, JSON.stringify(window.plugins.get(key)));
		}
	}
}


function adaptHeight() {
	var isH = document.getElementById('hasTableHeight');
	var h = document.getElementById('tableHeight');
	h.disabled = !isH.checked;
	
	if (isH.checked && h.value == '') h.value = '500';
	
	if (isH.checked && h.value != '') {
		dt.setHeight(parseInt(h.value));
	} else {
		isH.checked = false;
		h.value = '';
		dt.setHeight(null);
	}
}

function adaptWidth() {
	var isH = document.getElementById('hasTableWidth');
	var h = document.getElementById('tableWidth');
	h.disabled = !isH.checked;
	
	if (isH.checked && h.value == '') h.value = '500';
	
	if (isH.checked && h.value != '') {
		dt.setWidth(parseInt(h.value));
	} else {
		isH.checked = false;
		h.value = '';
		dt.setWidth(null);
	}
}